package com.aabte.memoryoverflow;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 *
 * -XX:MetaspaceSize=10m -XX:MaxMetaspaceSize=10m
 *
 * @author Daniel
 */
public class Metaspace {

    public static void main(String[] args) {

        try {
            long count = 0;
            while (true) {
                System.out.println("count = " + ++count);
                Enhancer enhancer = new Enhancer();
                enhancer.setSuperclass(Car.class);
                enhancer.setUseCache(false);
                enhancer.setCallback(new MethodInterceptor() {
                    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                        if (method.getName().equals("run")) {
                            System.out.println("启动汽车之前，先进行自动的安全检查...");
                            return methodProxy.invokeSuper(o,objects);
                        } else  {
                            return methodProxy.invokeSuper(o, objects);
                        }
                    }
                });

                Car car = (Car)enhancer.create();
                car.run();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static class Car {
        public void run() {
            System.out.println("Car run...");
        }
    }
}
